package com.huikeportal.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.write.Alignment;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.huikeportal.controller.common.ExcelCreate;
import com.huikeportal.controller.common.Lang;
import com.huikeportal.model.Language;
import com.huikeportal.model.ReportGraphData;
import com.huikeportal.model.ReportSiteDay;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteCommon;
import com.huikeportal.model.TodayIndexes;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.UserSiteHistory;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.CellVo;
import com.huikeportal.model.common.ExcelVo;
import com.huikeportal.model.common.SheetVo;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.CommonService;
import com.huikeportal.service.FootfallGlobalService;
import com.huikeportal.service.LoginService;
import com.huikeportal.service.MemcachedService;
import com.huikeportal.service.SelectSiteService;
import com.huikeportal.service.TodayIndexesService;

/**?
 *?2015-9-7?
 *?客流统计-全局分析
 *?author:wenyp?
 */
@Controller
@Scope("prototype")
public class FootfallGlobalController {

	@Autowired
	private HttpSession session;

	@Autowired
	private LoginService loginService;

	@Autowired
	private FootfallGlobalService footfallGlobalService;
	
	@Autowired
	private TodayIndexesService todayIndexesService;
	
	@Autowired
	private MemcachedService memcachedService;
	
	@Autowired
	SelectSiteService selectSiteService;
	
	@Autowired
	private CommonService commonService;
	

	/**初始化全局分析页面  */
	@RequestMapping("/footfallGlobal")
	public String footfallGlobalAnalysis( ModelMap model,String siteId) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
        userInfo = loginService.getUserInfo(userInfo); //得到用户信息
        String userId = userInfo.getUserId();
        //获取当前系统语言
        String sysLang = session.getAttribute("sysLang").toString();
        //查询当前页面id
        SqlParameter sql = new SqlParameter();
        sql.setSysLang(sysLang);
        sql.setString("footfallGlobal");
        Integer menuId = selectSiteService.getMenuId(sql);
        //获取用户权限按钮信息
        List<WordBook> buttonList = loginService.getUserButtonList(sysLang,
                userId, menuId);
        
        String buttonExport = "0";
        for(WordBook wordBook:buttonList){
        	if("导出".equals(wordBook.getDicValue())){
        		buttonExport = "1";
        		break;
        	}
        }
        /**初始化全局分析的指标权限*/
        /**获取用户指标权限*/
        List<String> userIndexList = footfallGlobalService.getUserIndex(userInfo);
        List<String> siteTypes = new ArrayList<String>();
        siteTypes.add(FootfallConstant.GLOBAL_SITETYPE);
        //我的数据_实时指标 model为1_1
        String moduleId1 = FootfallConstant.MYFOOTFALL_CUR;
        //我的数据_趋势分析 model为1_2
        String moduleId2 = FootfallConstant.MYFOOTFALL_TREND;
        //我的数据_指标明细 model为1_3
        String moduleId3 = FootfallConstant.MYFOOTFALL_DETIL;
        //我的数据-指标排行 model为1_4
        String moduleId4 = FootfallConstant.MYFOOTFALL_RANK;
        
        //获取实时指标	
        List<String> indexListCurrent = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId1, siteTypes);
        model.addAttribute("indexListCurrent ",indexListCurrent);
      //获取趋势分析指标详解
        List<String> indexListDetil = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId3, siteTypes);
        model.addAttribute("indexListDetil",indexListDetil);
        
        
        //获取趋势分析指标
        List<String> indexList = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId2, siteTypes);
        //取趋势分析指标分组
        HashMap<String, List<String>> indexListOfGroup = footfallGlobalService.getIndexListOfGroup(indexList);
        model.addAttribute("indexList",JSONObject.fromObject(indexListOfGroup));
        
        //获取排行榜各场所指标
        HashMap<String, Object> siteIndexMap = new HashMap<String, Object>();
        List<String> siteTypes200 = new ArrayList<String>();
        siteTypes200.add(FootfallConstant.DIQU_SITETYPE);
        List<String> index200 = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId4, siteTypes200);
        HashMap<String, List<String>> index200OfGroup = footfallGlobalService.getIndexListOfGroup(index200);
        siteIndexMap.put("index200",index200OfGroup);
        List<String> siteTypes300 = new ArrayList<String>();
        siteTypes300.add(FootfallConstant.WHOLE_SITETYPE);
        List<String> index300 = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId4, siteTypes300);
        HashMap<String, List<String>> index300OfGroup = footfallGlobalService.getIndexListOfGroup(index300);
        siteIndexMap.put("index300",index300OfGroup);
        List<String> siteTypes400 = new ArrayList<String>();
        siteTypes400.add(FootfallConstant.AREA_SITETYPE);
        List<String> index400 = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId4, siteTypes400);
        HashMap<String, List<String>> index400OfGroup = footfallGlobalService.getIndexListOfGroup(index400);
        siteIndexMap.put("index400",index400OfGroup);
        List<String> siteTypes500 = new ArrayList<String>();
        siteTypes500.add(FootfallConstant.FLOOR_SITETYPE);
        List<String> index500 = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId4, siteTypes500);
        HashMap<String, List<String>> index500OfGroup = footfallGlobalService.getIndexListOfGroup(index500);
        siteIndexMap.put("index500",index500OfGroup);
        List<String> siteTypes600 = new ArrayList<String>();
        siteTypes600.add(FootfallConstant.STORE_SITETYPE);
        List<String> index600 = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId4, siteTypes600);
        HashMap<String, List<String>> index600OfGroup = footfallGlobalService.getIndexListOfGroup(index600);
        siteIndexMap.put("index600",index600OfGroup);
        List<String> siteTypes700 = new ArrayList<String>();
        siteTypes700.add(FootfallConstant.CHANNEL_SITETYPE);
        List<String> index700 = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId4, siteTypes700);
        HashMap<String, List<String>> index700OfGroup = footfallGlobalService.getIndexListOfGroup(index700);
        siteIndexMap.put("index700",index700OfGroup);
        
        model.addAttribute("siteIndexMap",JSONObject.fromObject(siteIndexMap));
        
        //获取排行榜各时间指标
        HashMap<String, Object> dateIndexMap = new HashMap<String, Object>();
        List<String> indexHour  = footfallGlobalService.getTimeIndex("hour");
        dateIndexMap.put("indexHour", indexHour);
        List<String> indexDay  = footfallGlobalService.getTimeIndex("day");
        dateIndexMap.put("indexDay", indexDay);
        List<String> indexWeek  = footfallGlobalService.getTimeIndex("week");
        dateIndexMap.put("indexWeek", indexWeek);
        List<String> indexMonth  = footfallGlobalService.getTimeIndex("month");
        dateIndexMap.put("indexMonth", indexMonth);
        List<String> indexYear  = footfallGlobalService.getTimeIndex("year");
        dateIndexMap.put("indexYear", indexYear);
        model.addAttribute("dateIndexMap",JSONObject.fromObject(dateIndexMap));

        HashMap<String, String>  indexGroupInfo = footfallGlobalService.getIndexGroupInfo();
        model.addAttribute("indexGroupInfo",JSONObject.fromObject(indexGroupInfo));
        HashMap<String, String>  indexInfo = footfallGlobalService.getIndexInfo();
        model.addAttribute("indexInfo",JSONObject.fromObject(indexInfo));
        /**初始化全局分析的指标权限结束*/

        //根据用户信息查询设置位置
        String siteType = FootfallConstant.GLOBAL_SITETYPE; //场所类型是100
        String siteType300 = FootfallConstant.WHOLE_SITETYPE; //场所类型是300
        String siteID = "";
        SiteAllInfo siteAllInfo = footfallGlobalService.selectSiteByUserId(userInfo,
                siteType);
        String siteID300 = "";
        //siteAllInfo如果为空=没有集团权限；查找该用户的广场权限如果有场所权限取到该场所的集团siteId；如果没有则提示没有全局分析权限
        boolean judgeAll = true;//有集团权限judgeAll=true；没集团权限judgeAll=false；
        if (siteAllInfo == null||(siteAllInfo.getSiteid() == null) || "".equals(siteAllInfo.getSiteid())) {
            SiteAllInfo siteAllInfo1 = footfallGlobalService.selectSiteByUserId(userInfo,
                    siteType300);
            if ((siteAllInfo1.getSiteid() != null) &&
                    !"".equals(siteAllInfo1.getSiteid())) {
                //查询场所关系表获取上级集团的siteID
                siteID300 = footfallGlobalService.selectSiteRelationByChildId(siteAllInfo1.getSiteid().toString());
                judgeAll = false;
            }else{
            	String menuHtml = loginService.getMenuHtml(userInfo, "footfallGlobal");
    			model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
    			return "noPermission";	
            }
        }
		
		
//		String menuId=FootfallConstant.GLOBAL_MENUID;
		String sessionId=userId+menuId;
		UserSiteHistory userSiteHistory=new UserSiteHistory();;
		if(session.getAttribute(sessionId)!=null){
			userSiteHistory=(UserSiteHistory) session.getAttribute(sessionId);
		}
		
		//从seesion中取siteid
		//首先查找session找，然后是页面传过来，再是根据用户取
		if(siteId!=null&& !siteId.equals("")){
			siteID=siteId;
		}else{
			if(userSiteHistory.getSiteId()!=null&&!userSiteHistory.getSiteId().equals("")){
				siteID=userSiteHistory.getSiteId();
			}else {
				if(judgeAll){
					siteID=siteAllInfo.getSiteid();
				}else{
					siteID=siteID300;
				}
				
			}
		}
		
		//如果记录的siteId已经变更了，则取默认用户权限下的siteId
		SiteCommon siteCommon = selectSiteService.querySiteInfo(siteID);
		if(siteCommon == null){
			if(judgeAll){
				siteID=siteAllInfo.getSiteid();
			}else{
				siteID=siteID300;
			}
		}
		userSiteHistory.setSiteId(siteID);
		userSiteHistory.setUserId(userId);
		userSiteHistory.setMenuId(menuId);
//		footfallGlobalService.updateUserSiteHistory(userSiteHistory);//修改数据库记录
		session.setAttribute(sessionId, userSiteHistory);//如果没有将新得到的siteId存入session
		if(siteID!=null&& !siteID.equals("")){
			HashMap<String, Object> todayIndexes = new HashMap<String, Object>();
//			if(judgeAll){//如果有集团权限,
////				todayIndexes= todayIndexesService.getTodayIndexes(siteID,indexListCurrent);//edit by wenyapeng 2016-03-02:如果有集团权限，取集团下面所有的广场
////				todayIndexes = todayIndexesService.getTodayIndexesJituanAll(siteID,indexListCurrent);//废弃 取集团下面所有的广场 = 取集团部分，用户有所有广场的权限；
//				todayIndexes= todayIndexesService.getTodayIndexes(siteID,userInfo.getUserId(),indexListCurrent);
//			}else{//如果没有集团权限
//				todayIndexes= todayIndexesService.getTodayIndexes(siteID,userInfo.getUserId(),indexListCurrent);
//			}
			String siteNames=footfallGlobalService.getSiteNames(siteID);
			model.addAttribute("siteName", siteNames);
			model.addAttribute("siteId", siteID);
			model.addAttribute("datetime", footfallGlobalService.getDate());
			model.addAttribute("todayIndexes",todayIndexes);
		}
		model.addAttribute("judgeAll",judgeAll);
		model.addAttribute("buttonExport",buttonExport);
		Language lang = Lang.getInfo(sysLang);
		model.addAttribute("lang",lang);
		String menuHtml = loginService.getMenuHtml(userInfo, "footfallGlobal");//设置左侧列表菜单
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		return "footfallGlobal";
	}
	
	/**前台获取图表数据  */
	@SuppressWarnings("deprecation")
	@RequestMapping("/getGlobalAnalysis")
	@ResponseBody
	public HashMap<String , Object> getGraphData(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
//		StringBuffer name1=request.get
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		String type= request.getParameter("type").toString();//获取type类型 1是"客流";2是 "销售额";3是 "提袋率";4是 "客单价";5是 "人效";6 "坪效";7 "集客力";其他 "平均滞留时间";
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		//日周月年
		String timeType_table=Strings[0];
		//类型1、2小时，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
		//图表的开始时间
		String startDate=request.getParameter("from").toString();//获取几天的数据
		//如表的结束时间
		String endDate=request.getParameter("to").toString();//获取几天的数据
		
		String siteId=request.getParameter("siteId");//获取几天的数据
//		比较图表的开始时间
		String compareStartDate=request.getParameter("from2").toString();;
//		比较图表的结束时间
		String compareEndDate=request.getParameter("to2").toString();
		
		HashMap<String , Object> paraMapResult=new HashMap<String, Object>();
		
		//查询图表
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("timeType", timeType);
		paraMap.put("timeType_table", timeType_table);//日周月年表
		paraMap.put("startDate", startDate);
		paraMap.put("endDate", endDate);
		paraMap.put("type", type);
		paraMap.put("siteId", siteId);
		paraMap.put("userInfo", userInfo);
		List<ReportGraphData> list= footfallGlobalService.getGraphData(paraMap);
		List<String> siteType = footfallGlobalService.getSiteTypes(siteId);
		/** 获取siteId 的场所类型中文名称*/
		String siteTypeName = "";
		if(siteType!=null&&!"".equals(siteType)){
			String siteType1 = siteType.get(0);
			siteTypeName = footfallGlobalService.getSiteTypeName(Integer.parseInt(siteType1));
		}
		paraMapResult.put("siteTypeName", siteTypeName);
		
		List<ReportGraphData> compareList = new ArrayList<ReportGraphData>();
		/*查询比较图表*/
		if(compareStartDate!=""&&"0".equals(timeType)){
			HashMap<String , Object> compareParaMap=new HashMap<String, Object>();
			compareParaMap.put("timeType", timeType);
			compareParaMap.put("timeType_table", timeType_table);//日周月年表
			compareParaMap.put("startDate", compareStartDate);
			compareParaMap.put("endDate", compareEndDate);
			compareParaMap.put("type", type);
			compareParaMap.put("siteId", siteId);
			compareParaMap.put("userInfo", userInfo);
			compareList= footfallGlobalService.getGraphData(compareParaMap);
			paraMapResult.put("compareResult", compareList);
//			paraMapResult.put("compstadubiao", compareList.get(0).getDatatime());
//			paraMapResult.put("compendtubiao", compareList.get(compareList.size()-1).getDatatime());
			if("hour".equals(timeType_table)){
				if(compareList.size()>0){
					paraMapResult.put("compstadubiao", compareList.get(0).getDate());
				}else{
					paraMapResult.put("compstadubiao", compareStartDate);
				}
//				paraMapResult.put("compendtubiao", compareList.get(compareList.size()-1).getDatatime());
			}else if("day".equals(timeType_table)){
				paraMapResult.put("compstadubiao", compareList.get(0).getDatatime());
				paraMapResult.put("compendtubiao", compareList.get(compareList.size()-1).getDatatime());
			}else if("week".equals(timeType_table)){
				paraMapResult.put("compstadubiao", compareList.get(0).getYear()+"-"+compareList.get(0).getWeek());
				paraMapResult.put("compendtubiao", compareList.get(compareList.size()-1).getYear()+"-"+compareList.get(compareList.size()-1).getWeek());
			}else if("month".equals(timeType_table)){
				paraMapResult.put("compstadubiao", compareList.get(0).getYear()+"-"+compareList.get(0).getMonth());
				paraMapResult.put("compendtubiao", compareList.get(compareList.size()-1).getYear()+"-"+compareList.get(compareList.size()-1).getMonth());
			}else{
				paraMapResult.put("compstadubiao", compareList.get(0).getYear());
				paraMapResult.put("compendtubiao", compareList.get(compareList.size()-1).getYear());
			}
		}
		
		//插入数据日期类型，日周年月
		paraMapResult.put("timeType_table",timeType_table);
		//插入折线数据
		paraMapResult.put("result", list);
		//表格数据
		List<ReportGraphData> tableList = new ArrayList<ReportGraphData>();
		//加入数据
		for(ReportGraphData reportGraphData :list){
			tableList.add(reportGraphData);
		}
		//去重
		tableList.removeAll(compareList);
		//加入对比数据
		for(ReportGraphData reportGraphData :compareList){
			tableList.add(reportGraphData);
		}
		//获取表格数据
//		StringBuffer loadTable=getGlobalTable(tableList,timeType_table,userInfo,siteId);//自定义样式型
		StringBuffer loadTable=getGlobalTable1(tableList,timeType_table,userInfo,siteId);//利用插件型
//		String loadTable="<table id='tabledata'><thead><tr><th width='150px'>编号</th><th  width='100px'>日期</th><th  width='100px'>星期</th><th width='100px'>客流量（人次）</th><th width='100px'>销售额（元）</th><th width='100px'>顾客数（人）</th><th width='100px'>会员人数（人）</th></tr></thead><tbody><tr><td  width='100px'>1</td><td width='100px'>2016-01-05</td><td width='100px'>星期二</td><td width='100px'>0</td><td width='100px'>0</td><td width='100px'>0</td><td width='100px'>0</td></tr><tr><td >2</td><td>2016-01-06</td><td>星期三</td><td>0</td><td>0</td><td>0</td><td>0</td></tr><tr><td >3</td><td>2016-01-07</td><td>星期四</td><td>0</td><td>0</td><td>0</td><td>0</td></tr><tr><td >4</td><td>2016-01-08</td><td>星期五</td><td>0</td><td>0</td><td>0</td><td>0</td></tr><tr><td >5</td><td>2016-01-09</td><td>星期六</td><td>0</td><td>0</td><td>0</td><td>0</td></tr><tr><td >6</td><td>2016-01-10</td><td>星期日</td><td>0</td><td>0</td><td>0</td><td>0</td></tr><tr><td >7</td><td>2016-01-11</td><td>星期一</td><td>0</td><td>0</td><td>0</td><td>0</td></tr></tbody></table>";
//		String loadTable="<table id='tabledata'><thead><tr><th width='80'>设备ID</th><th width='80'>comment</th><th width='80'>status</th><th width='80'>major</th><th width='80'>minor</th><th width='80'>uuid</th><th width='80'>设备ID</th><th width='80'>comment</th><th width='80'>status</th><th width='80'>major</th><th width='80'>minor</th><th width='80'>uuid</th><th width='80'>设备ID</th><th width='80'>comment</th><th width='80'>status</th><th width='80'>major</th><th width='80'>minor</th><th width='80'>uuid</th></tr></thead><tbody><tr><td>1</td><td>1</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>你好</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>3</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>4</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>6</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>7</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>8</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>9</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>10</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>11</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>12</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr><tr><td>1</td><td>13</td><td>3</td><td>4</td><td>5</td><td>10</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr></tbody></table>";
		//放入表格数据
		paraMapResult.put("loadTable", loadTable);
//		String siteN=todayIndexesService.getSiteNameBySiteId(siteId);//场所中文名称
		String siteNames=footfallGlobalService.getSiteNames(siteId);//前台导航栏地址 广场-场所
		paraMapResult.put("siteN", siteNames);
		String sitename=footfallGlobalService.getSiteName(siteId);//siteId的中文名称
		paraMapResult.put("siteName", sitename);
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
		if("hour".equals(timeType_table)){
			if(list.size()>0){
				paraMapResult.put("stadubiao", list.get(0).getDate());
			}else{
				if("1".equals(timeType)){
					Date date=new Date();
					paraMapResult.put("stadubiao", sf.format(date));
				}else if("2".equals(timeType)){
					Date date=new Date();
					date.setDate(date.getDate()-1);
					paraMapResult.put("stadubiao", sf.format(date));
				}else{
					paraMapResult.put("stadubiao", startDate);	
				}
				
			}
//			paraMapResult.put("endtubiao", list.get(list.size()-1).getDatatime());
		}else if("day".equals(timeType_table)){
			paraMapResult.put("stadubiao", list.get(0).getDatatime());
			paraMapResult.put("endtubiao", list.get(list.size()-1).getDatatime());
		}else if("week".equals(timeType_table)){
			paraMapResult.put("stadubiao", list.get(0).getYear()+"-"+list.get(0).getWeek());
			paraMapResult.put("endtubiao", list.get(list.size()-1).getYear()+"-"+list.get(list.size()-1).getWeek());
		}else if("month".equals(timeType_table)){
			paraMapResult.put("stadubiao", list.get(0).getYear()+"-"+list.get(0).getMonth());
			paraMapResult.put("endtubiao", list.get(list.size()-1).getYear()+"-"+list.get(list.size()-1).getMonth());
		}else{
			paraMapResult.put("stadubiao", list.get(0).getYear());
			paraMapResult.put("endtubiao", list.get(list.size()-1).getYear());
		}
		
		return paraMapResult;
	}
	
	
	/**前台获取图表数据  */
	public StringBuffer getGlobalTable(List<ReportGraphData> list,String timeType_table,UserInfo userInfo,String siteId) throws Exception {
		return footfallGlobalService.getGlobalTable(list,timeType_table,userInfo,siteId);
	}
	
	/**
	 * 前台利用插件拼table
	 * @param list
	 * @param timeType_table
	 * @param userInfo
	 * @param siteId
	 * @return
	 * @throws Exception
	 */
	public StringBuffer getGlobalTable1(List<ReportGraphData> list,String timeType_table,UserInfo userInfo,String siteId) throws Exception {
		return footfallGlobalService.getGlobalTable1(list,timeType_table,userInfo,siteId);
	}
	
	
	
	/**前台获取排行榜数据 
	 * @deprecated 已不用
	 *  */
	@RequestMapping("/footPaiHang")	
	@ResponseBody
	public HashMap<String , Object> getfootPaiHang(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		//场所
		String siteKey= request.getParameter("siteId");
		//指标
		int type= Integer.parseInt(request.getParameter("type"));
//		时间
		String span= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =span.split("_");
		//日周月年
		String timeType_table=Strings[0];
		//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
//		子场所类型
		String rankingType=request.getParameter("rankingType").toString();
		String from= request.getParameter("from").toString();
		String to= request.getParameter("to").toString();
		String orderBy= request.getParameter("orderBy").toString();
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("rankingType", rankingType);
		paraMap.put("startDate", from);
		paraMap.put("endDate", to);
		paraMap.put("siteId", siteKey);
		paraMap.put("type", type);
		paraMap.put("span", span);
		paraMap.put("timeType_table", timeType_table);
		paraMap.put("timeType", timeType);
		paraMap.put("orderBy", orderBy);
		paraMap.put("userInfo", userInfo);
		List<HashMap<String,Object>>  stringRank=footfallGlobalService.getfootPaiHang(paraMap);
		
		paraMap.put("result", stringRank);
		return paraMap;
	}
	
	/**前台获取排行榜数据  */
	@RequestMapping("/getGlobalRanking")	
	@ResponseBody
	public HashMap<String , Object> getGlobalRanking(HttpServletRequest request,HttpServletResponse response) throws Exception {
		//场所
		String siteId= request.getParameter("siteId");
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		int type= Integer.parseInt(request.getParameter("type"));
		String from= request.getParameter("from").toString();
		String to= request.getParameter("to").toString();
		String span= request.getParameter("span").toString();
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		//日周月年
		String timeType_table=Strings[0];
		//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
		
		String orderBy= request.getParameter("orderBy").toString();
		
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("startDate", from);
		paraMap.put("endDate", to);
		paraMap.put("siteId", siteId);
		paraMap.put("type", type);
		paraMap.put("span", span);
		paraMap.put("timeType_table", timeType_table);
		paraMap.put("timeType", timeType);
		paraMap.put("orderBy", orderBy);
		paraMap.put("userInfo", userInfo);
		List<HashMap<String,Object>> stringRank=footfallGlobalService.getRanking(paraMap);
		
		paraMap.put("result", stringRank);
		return paraMap;
	}
	
	@RequestMapping("/getGlobalExportExcle")
	@ResponseBody
	public HashMap<String , Object> getGlobalExportExcle(HttpServletRequest request,HttpServletResponse response) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
//		StringBuffer name1=request.get
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		String type= request.getParameter("type").toString();//获取type类型 1是"客流";2是 "销售额";3是 "提袋率";4是 "客单价";5是 "人效";6 "坪效";7 "集客力";其他 "平均滞留时间";
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		//日周月年
		String timeType_table=Strings[0];
		//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
		//图表的开始时间
		String startDate=request.getParameter("from").toString();//获取几天的数据
		//如表的结束时间
		String endDate=request.getParameter("to").toString();//获取几天的数据
		
		String fileName = request.getParameter("fileName").toString();//excel表名称
		
		String siteId=request.getParameter("siteId");//获取几天的数据
//		比较图表的开始时间
		String compareStartDate=request.getParameter("from2").toString();;
//		比较图表的结束时间
		String compareEndDate=request.getParameter("to2").toString();
		
		HashMap<String , Object> paraMapResult=new HashMap<String, Object>();
		//查询图表
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("timeType", timeType);
		paraMap.put("timeType_table", timeType_table);//日周月年表
		paraMap.put("startDate", startDate);
		paraMap.put("endDate", endDate);
		paraMap.put("type", type);
		paraMap.put("siteId", siteId);
		paraMap.put("userInfo", userInfo);
		List<ReportGraphData> list= footfallGlobalService.getGraphData(paraMap);
		
		/*查询比较图表*/
		if(compareStartDate!=""&&"0".equals(timeType)){
		HashMap<String , Object> compareParaMap=new HashMap<String, Object>();
		compareParaMap.put("timeType", timeType);
		compareParaMap.put("timeType_table", timeType_table);//日周月年表
		compareParaMap.put("startDate", compareStartDate);
		compareParaMap.put("endDate", compareEndDate);
		compareParaMap.put("type", type);
		compareParaMap.put("siteId", siteId);
		compareParaMap.put("userInfo", userInfo);
		List<ReportGraphData> compareList= footfallGlobalService.getGraphData(compareParaMap);
		paraMapResult.put("compareResult", compareList);
		}
		
		//插入数据日期类型，日周年月
		paraMapResult.put("timeType_table",timeType_table);
		//插入折线数据
		paraMapResult.put("result", list);
		//获取表格数据
		StringBuffer loadTable=getGlobalTable(list,timeType_table,userInfo,siteId);
		String table=loadTable.toString();
		ArrayList<String[]> tables=footfallGlobalService.changeTableToList(table);
		//新建excel对象
		ExcelVo excelVo = new ExcelVo();
		//设置excel文件名
		String name = "";
		if("".equals(fileName)){
			name = "详细数据"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		}else {
			name = fileName.split("：")[1];
		}
		excelVo.setFileName(name);
		// 标题数组
//		String[] titleArray = tables.get(0);
		// 创建sheet
		SheetVo sheetVo = new SheetVo();
		sheetVo.setSheetNo(1);
		sheetVo.setName("详细数据");
		excelVo.addSheet(sheetVo);
		// 创建单元格
		CellVo cellVoFirst = new CellVo();
		
		for (int i = 0; i < tables.size(); i++) {
			String[] tables1 =  tables.get(i);
			// 内容数组
			String[] contentArray = tables1;
			
			for(int j = 0;j<contentArray.length;j++){
				 cellVoFirst = new CellVo();
				 cellVoFirst.setText(contentArray[j]);
				 cellVoFirst.setColNo(j);
				 cellVoFirst.setRowNo(i+1);
				 cellVoFirst.setFormat(new WritableCellFormat());
				 sheetVo.addCell(cellVoFirst);
			}
		}
		//导出excel
		ExcelCreate.createExcel(excelVo, response,"utf-8");
		HashMap<String , Object> paraMap1=new HashMap<String, Object>();
		paraMap1.put("result", name);
		return paraMap1;
	}
	
	@RequestMapping("/getExportExcle")
	@ResponseBody
	public HashMap<String , Object> getExportExcle(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		String table=request.getParameter("table").toString();
		table = java.net.URLDecoder.decode(table,"UTF-8"); 
		
		String fileName = request.getParameter("fileName").toString();
		fileName = java.net.URLDecoder.decode(fileName,"UTF-8"); 
		
		String character =  request.getParameter("character").toString();
		character = java.net.URLDecoder.decode(character,"UTF-8"); 
		
		String describe =  request.getParameter("describe").toString();
		describe = java.net.URLDecoder.decode(describe,"UTF-8"); 
		describe = describe.replace("<br>", "");
		String[] strs = new String[8];;
		strs[0] = describe;
		ArrayList<String[]> tables=footfallGlobalService.changeTableToList(table);
		ArrayList<String[]> tablesExcle = new ArrayList<String[]>();
		for(String[] row:tables){
			List<String> list = new ArrayList<String>();  
	        for (int i=0; i<row.length; i++) {
	            list.add(row[i]);  
	        }  
	        String[] newStr =  list.toArray(new String[1]); //返回一个包含所有对象的指定类型的数组   
	        tablesExcle.add(newStr);
		}
		
		tablesExcle.add(0, strs);
		//新建excel对象
		ExcelVo excelVo = new ExcelVo();
		//设置excel文件名
		String name = "";
//		if("".equals(fileName)){
//			name="详细数据"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//		}else{
//			name = fileName.split("：")[1];
//		}
		excelVo.setFileName(fileName);
		// 标题数组
//		String[] titleArray = tables.get(0);
		// 创建sheet
		SheetVo sheetVo = new SheetVo();
		sheetVo.setSheetNo(1);
		sheetVo.setName("详细数据");
		excelVo.addSheet(sheetVo);
		// 创建单元格
		CellVo cellVoFirst = new CellVo();
		
		WritableFont font1 =new WritableFont(WritableFont.createFont("宋体"), 10 ,WritableFont.BOLD);  
        WritableFont font2 =new WritableFont(WritableFont.createFont("宋体"), 10 ,WritableFont.NO_BOLD);
        WritableFont font3 =new WritableFont(WritableFont.createFont("宋体"), 10 ,WritableFont.NO_BOLD);
        WritableFont font4 =new WritableFont(WritableFont.createFont("宋体"), 10 ,WritableFont.NO_BOLD);
        WritableCellFormat wcf1 = new WritableCellFormat(font1);  
        WritableCellFormat wcf2 = new WritableCellFormat(font2);  
        WritableCellFormat wcf3 = new WritableCellFormat(font3);  
        WritableCellFormat wcf4 = new WritableCellFormat(font4);  
        wcf1.setAlignment(Alignment.CENTRE);  //平行居中  
        wcf2.setAlignment(Alignment.CENTRE);  //平行居中  
        wcf3.setAlignment(Alignment.RIGHT);  //平行居右
        wcf4.setAlignment(Alignment.LEFT);  //平行居右
        
		for (int i = 0; i < tablesExcle.size(); i++) {
			String[] tables1 =  tablesExcle.get(i);
			// 内容数组
			String[] contentArray = tables1;
			
			for(int j = 0;j<contentArray.length;j++){
				 cellVoFirst = new CellVo();
				 cellVoFirst.setText(contentArray[j]);
				 cellVoFirst.setColNo(j);
				 cellVoFirst.setRowNo(i+1);
				 if(i==0){
					 cellVoFirst.setFormat(wcf4);
				 }
				 if(i==1){
					 cellVoFirst.setFormat(wcf1);
				 }else{
					 if(j==0){
						 cellVoFirst.setFormat(wcf2);
					 } else{
						 String testStr = contentArray[j];
						 if(testStr!=null){
							 String testStrnew  = testStr.replace(",","");
							 if(isDecimal(testStrnew)){
								 cellVoFirst.setFormat(wcf3);
							 }else{
								 cellVoFirst.setFormat(wcf2);
							 }
						 }else{
							 	cellVoFirst.setFormat(wcf2);
						}
					 }
				}
				 
				 sheetVo.addCell(cellVoFirst);
			}
		}
		//导出excel
		ExcelCreate.createExcelForReport(excelVo, response,character);
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("result", name);
		return paraMap;
	}
	
	public  boolean isDecimal(String str){  
		  return Pattern.compile("^\\d+(\\.\\d+)?$").matcher(str).matches();  
		 }  
	
	@RequestMapping("/ifTestAcount")
	@ResponseBody
	public HashMap<String , String> ifTestAcount(HttpServletRequest request,HttpServletResponse response) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
        userInfo = loginService.getUserInfo(userInfo); //得到用户信息
        String userName = userInfo.getUserName();
        String juge = getUpperUser(userName);
		HashMap<String , String> paraMap=new HashMap<String, String>();
		paraMap.put("juge",juge);
		return paraMap;
	}
	private String getUpperUser(String createUserId) throws Exception {
		String juge = "1";
		String userName = createUserId;
		UserInfo userInfo = new UserInfo();
		userInfo.setUserName(userName);
        userInfo = loginService.getUserInfo(userInfo); //得到用户信息
        if(userInfo==null){
        	return juge;
        }
        String createUser = userInfo.getCreateUserId();
        String user = userInfo.getUserName();
        if("jituan".equals(createUser)||"jituan".equals(user)){
        	juge = "0";
        }else if(createUser != null && !"".equals(createUser)){
        	juge = getUpperUser(createUser);
        }
		return juge;
	}
	/**
	 * 获取指标顺序
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getIndexOrder")
	@ResponseBody
	public HashMap<String ,  List<String>> getIndexOrder(HttpServletRequest request,HttpServletResponse response) throws Exception {
		HashMap<String ,  List<String>> paraMap= footfallGlobalService.getIndexOrder();
		return paraMap;
	}
	
	/**
	 * 获取今日指标
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/getTodayTarget")
	@ResponseBody
	
	public HashMap<String, String> getTodayTarget(HttpServletRequest request,HttpServletResponse response) throws Exception{
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
        userInfo = loginService.getUserInfo(userInfo); //得到用户信息
        String judgeAll = request.getParameter("judgeAll").toString();
        String siteId = request.getParameter("siteId").toString();
        //获取实时指标	
        /**初始化全局分析的指标权限*/
        /**获取用户指标权限*/
        List<String> userIndexList = footfallGlobalService.getUserIndex(userInfo);
        List<String> siteTypes = new ArrayList<String>();
        siteTypes.add(FootfallConstant.GLOBAL_SITETYPE);
        //我的数据_实时指标 model为1_1
        String moduleId1 = FootfallConstant.MYFOOTFALL_CUR;
        //我的数据_趋势分析 model为1_2
        String moduleId2 = FootfallConstant.MYFOOTFALL_TREND;
        //我的数据_指标明细 model为1_3
        String moduleId3 = FootfallConstant.MYFOOTFALL_DETIL;
        //我的数据-指标排行 model为1_4
        String moduleId4 = FootfallConstant.MYFOOTFALL_RANK;
		HashMap<String, Object> todayIndexes = new HashMap<String, Object>();
        List<String> indexListCurrent = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId1, siteTypes);
		if(judgeAll.equals("true")){//如果有集团权限,
			todayIndexes= todayIndexesService.getTodayIndexes(siteId,userInfo.getUserId(),indexListCurrent);
		}else{//如果没有集团权限
			todayIndexes= todayIndexesService.getTodayIndexes(siteId,userInfo.getUserId(),indexListCurrent);
		}
		String TodayTargetStr = footfallGlobalService.getTodayTargetStr(todayIndexes);
		HashMap<String, String> result = new HashMap<String, String>();
		result.put("result", TodayTargetStr);
		return result;
	}
	

}
